// miniprogram/pages/user/index/index.js
import {getRecordCount} from "../../../service/Record"
import {getHelperCount} from "../../../service/User"
import {getStorageSync} from "../../../utils/Storage"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        pageShow: false,
        nickName: "",
        avatarUrl: "",
        version: "v1.0", //当前版本号
        lostCount: 0,
        foundCount: 0,
        checkAuthorize: false //组件授权校验
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let accountInfo = wx.getAccountInfoSync ? wx.getAccountInfoSync() : {};
        let version = accountInfo.miniProgram.version;
        let usrInfo = getStorageSync("userInfo") || {}
        this.setData({
            authorized: !!usrInfo.authorized,
            nickName: usrInfo.nickName || "点击头像授权",
            avatarUrl: usrInfo.avatarUrl || "/images/default-photo.png",
            version: version || "v1.0",
            checkAuthorize: true
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getUserCount()
    },

    /*
    * 授权组件接收函数
    * */
    onAuthorizeBtn: function (e) {
        let result = e.detail.result;
        let name = e.currentTarget.dataset.name;
        this.setData({
            authorized: result.authorized,
            nickName: result.nickName,
            avatarUrl: result.avatarUrl,
            checkAuthorize: true
        })
        name ? wx.navigateTo({
          url: ""
        }) : null
    },

    /*
    * 获取记录数量
    * */
    getUserCount: async function () {
        try {
            let record = await getRecordCount();
            let helperRes = await getHelperCount();
            this.setData({
                lostTotal: record.lostTotal,
                foundTotal: record.foundTotal,
                helperTotal: helperRes.total,
                pageShow: true
            })
        } catch (e) {
            console.error(e)
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    onShareTimeline: function () {}
})